package jcu.salt.io;

import java.io.IOException;

import jcu.salt.Configuration;
import jcu.salt.client.DataHandler;


/**
 * Provides convenient access to a data turbine connection
 * to delegate handling of data received to a given {@link DataHandler}.
 * 
 * @author SAL-T team
 *
 */
public class Receiver {

	private String turbineIP;
	private String turbineSource;
	private String turbineSink;
	private String turbineChannel;
	private DataTurbineReadConnector dtrconn;
	private boolean active;

	public Receiver(String ip, String source, String sink, String channel) {
		turbineIP = ip;
		turbineSource = source;
		turbineSink = sink;
		turbineChannel = channel;
	}

	public Receiver(String channel) {
		Configuration config = Configuration.getInstance();
		turbineIP = config.get(Configuration.DATATURBINE_IP);		
		turbineSink = config.get(Configuration.SINK);
		
		int idx = channel.indexOf('/');
		if(idx == -1) {
		
		turbineSource = config.get(Configuration.SOURCE);
		turbineChannel = channel;
		} else {
			turbineSource =  channel.substring(0, idx);
			turbineChannel = channel.substring(idx+1, channel.length());
		}
	}

	public Receiver() {
		Configuration config = Configuration.getInstance();
		turbineIP = config.get(Configuration.DATATURBINE_IP);
		turbineSource = config.get(Configuration.SOURCE);
		turbineSink = config.get(Configuration.SINK);
		turbineChannel = config.get(Configuration.DEFAULTCHANNEL);
	}
	
	public void receive(DataHandler handler) {
		if (isConnected()) {
			setActive(true);
			while (isActive()) {
				try {
					dtrconn.read(2000, handler); // block for 2000 msec
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	public void connect() {
		if (!isConnected()) {
			dtrconn = new DataTurbineReadConnector(turbineIP, turbineSource,
					turbineSink, turbineChannel);
		}
	}

	public boolean isConnected() {
		return dtrconn != null && dtrconn.isConnected();
	}

	public void disconnect() {
		if (isConnected()) {
			try {
				dtrconn.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			dtrconn = null;
		}
	}

	public String getChannel() {
		return turbineChannel;
	}

	public void setActive(boolean active) {
		if(isActive() && active == false) {
			dtrconn.setRead(active);
		}
		this.active = active;
	}

	private boolean isActive() {
		return active;
	}

}
